package wxk.interview.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author wangxuekai
 * @version 2.2
 * @Date 2017/3/8.
 * @since 2.2
 */
public class MyCallableThread {

    public static void main(String[] args){
        long srt = System.currentTimeMillis();
        MyCallableThread t = new MyCallableThread();
        try {
            t.exec();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("运行时间>>"+(end-srt)+"ms.");
    }

    private void exec() throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        List<Future> list = new ArrayList<Future>();
        for (int i = 0; i < 5; i++){
            MyCallable callable = new MyCallable("task"+i);
            list.add(pool.submit(callable));
        }
        pool.shutdown();

        for (Future f : list){
            System.out.println(f.get().toString());
        }
    }

    class MyCallable implements Callable<String>{
        private String taskNum;

        public MyCallable() {
        }

        public MyCallable(String taskNum) {
            this.taskNum = taskNum;
        }

        public String call() throws Exception {
            System.out.println(">>>"+taskNum+"任务开始启动");
            long start = System.currentTimeMillis();
            Thread.sleep(1000);
            long end = System.currentTimeMillis();
            System.out.println(">>>"+taskNum+"任务终止");
            return taskNum+" 任务返回运行结果,运行时间为["+(end-start)+"ms.]";
        }


    }
}
